<?php
/**
 * Function:
 * Description:
 * Abo 2018/10/10 20:41
 * Email: abo2013@foxmail.com
 */

//创建websocket服务器对象，监听0.0.0.0:9502端口
$ws = new swoole_websocket_server("0.0.0.0", 8812);
static $session = [];

// 静态资源返回 http://127.0.0.1:8812/js/ws_client.html
$ws->set([
    'enable_static_handler' => true,
    'document_root' => '/Users/abo_o/Dev/workplace/php/swoole2_practice/demo/static',
]);

//监听WebSocket连接打开事件
$ws->on('open', function ($ws, $request) {
    $session[ 'open_clients' ][] = $request->fd;
    // var_dump($request->fd, $request->get, $request->server);
    $ws->push($request->fd, "hello, welcome\n");
    var_dump( $_SESSION );
});

//监听WebSocket消息事件
$ws->on('message', function ($ws, $frame) {
    echo "{$frame->fd}Message: {$frame->data},opcode:{$frame->opcode},fin:{$frame->finish}\n";
    $ws->push($frame->fd, "WebSocket server: {$frame->data}");
});

//监听WebSocket连接关闭事件
$ws->on('close', function ($ws, $fd) {
    echo "client-{$fd} is closed\n";
});

$ws->start();